package com.jie.crm.config;

import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.jie.crm.common.R;
import com.jie.crm.common.R.Pagination;

/**
 * 解析请求参数，主要是分页参数和查询参数
 * @author wangjie
 *
 */
public class RResolver implements HandlerMethodArgumentResolver {

	@Override
	public boolean supportsParameter(MethodParameter parameter) {
		return parameter.getParameterType().equals(R.class);
	}

	@Override
	public Object resolveArgument(MethodParameter parameter,
			ModelAndViewContainer mavContainer, NativeWebRequest webRequest,
			WebDataBinderFactory binderFactory) throws Exception {
		R r = new R();
		String pageNumber = webRequest.getParameter("page");
		String pageSize = webRequest.getParameter("rows");
		if (StringUtils.isNotBlank(pageNumber)
				&& StringUtils.isNotBlank(pageSize)) {
			Pagination page = new Pagination();
			page.setPage(Integer.valueOf(pageNumber));
			page.setRows(Integer.valueOf(pageSize));
			r.setPage(page);
		}
		String dataJson = webRequest.getParameter("dataMap");
		if (StringUtils.isNotBlank(dataJson)) {
			ObjectMapper mapper = new ObjectMapper();
			mapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
			mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
			TypeReference<Map<String, Object>> typeRef = new TypeReference<Map<String, Object>>() {
			};
			Map<String, Object> dataMap = mapper.readValue(dataJson, typeRef);
			r.putData(dataMap);
		}
		return r;
	}

}
